package cn.aitrox.ry.service.dwh.service.impl;

import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.common.exception.CustomBizException;
import cn.aitrox.ry.common.service.BaseService;
import cn.aitrox.ry.enumtype.RespCodeEnum;
import cn.aitrox.ry.service.dwh.dto.DwhImageDto;
import cn.aitrox.ry.service.dwh.dto.out.jy.ImageItemDto;
import cn.aitrox.ry.service.dwh.dto.out.jy.SeriesItemDto;
import cn.aitrox.ry.service.dwh.remote.JyDwhApi;
import cn.aitrox.ry.service.dwh.service.ImageService;
import cn.aitrox.ry.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ImageServiceImpl extends BaseService implements ImageService {

    @Autowired
    private JyDwhApi jyDwhApi;

    @Override
    public RespResult<Map<String, List<DwhImageDto>>> imageQuery(List<String> seriesUids) {
        if (ArrayUtil.isEmpty(seriesUids)) {
            return RespResult.ok(new HashMap<>());
        }
        Map<String, List<DwhImageDto>> map = new HashMap<>();
        List<SeriesItemDto> seriesItemList = jyDwhApi.seriesQuery(seriesUids);
        Map<String, SeriesItemDto> seriesMap = seriesItemList.stream().collect(Collectors.toMap(SeriesItemDto::getSeriesInstanceUID, x -> x, (k1, k2) -> k1));
        try {
            seriesUids.forEach(seriesUid -> {
                SeriesItemDto seriesItem = seriesMap.get(seriesUid);
                if (null == seriesItem) {
                    throw new CustomBizException("序列不存在: " + seriesUid);
                }
                List<ImageItemDto> imageItemList = jyDwhApi.imageQuery(seriesUid, seriesItem.getFileType());
                List<DwhImageDto> imageList = imageItemList.stream().map(x -> new DwhImageDto(seriesUid, x.getNumber(), x.getFileType(), x.getPath(), x.getUrlLAN(), x.getUrlWAN())).collect(Collectors.toList());
                map.put(seriesUid, imageList);
            });
        } catch (Exception e) {
            return RespResult.secByError(RespCodeEnum.ERROR.getCode(), e.getMessage());
        }
        return RespResult.ok(map);
    }
}
